package edu.ustb.efws.pipeline.collect;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 采集线程Factory
 *
 * @author TS Group
 */
public class CollectThreadFactory implements ThreadFactory {
    private final AtomicInteger counter = new AtomicInteger();

    private final String namePrefix;
    private final int priority;
    private final ThreadGroup group;

    /**
     * 构造{@link CollectThreadFactory}
     */
    CollectThreadFactory(){
        this("collect-worker-", 6);
    }

    /**
     * 构造{@link CollectThreadFactory}
     *
     * @param namePrefix 线程前缀名
     * @param priority 线程运行优先级
     */
    CollectThreadFactory(String namePrefix, int priority){
        this.namePrefix = namePrefix;
        this.priority = priority;
        SecurityManager s = System.getSecurityManager();
        this.group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = namePrefix + counter.incrementAndGet();
        Thread thread = new Thread(group, r, name);
        thread.setPriority(priority);

        return thread;
    }
}
